import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH = 288
HEIGHT = 512
GRAVITY = 0.25
BIRD_JUMP = -6
PIPE_GAP = 150
PIPE_VEL = 2
WHITE = (255, 255, 255)

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("像素鸟游戏")

# 小鸟类
class Bird:
    def __init__(self):
        self.x = 50
        self.y = HEIGHT // 2
        self.vel = 0

    def jump(self):
        self.vel = BIRD_JUMP

    def move(self):
        self.vel += GRAVITY
        self.y += self.vel

    def draw(self):
        pygame.draw.circle(screen, WHITE, (self.x, int(self.y)), 10)

# 管道类
class Pipe:
    def __init__(self):
        self.x = WIDTH
        self.height = random.randint(50, 300)
        self.gap_y = random.randint(100, HEIGHT - PIPE_GAP - 100)
        self.passed = False

    def move(self):
        self.x -= PIPE_VEL

    def draw(self):
        pygame.draw.rect(screen, WHITE, (self.x, 0, 50, self.gap_y))
        pygame.draw.rect(screen, WHITE, (self.x, self.gap_y + PIPE_GAP, 50, HEIGHT - self.gap_y - PIPE_GAP))

    def collides_with(self, bird):
        bird_rect = pygame.Rect(self.x, int(bird.y - 10), 20, 20)
        top_pipe_rect = pygame.Rect(self.x, 0, 50, self.gap_y)
        bottom_pipe_rect = pygame.Rect(self.x, self.gap_y + PIPE_GAP, 50, HEIGHT - self.gap_y - PIPE_GAP)
        return (bird_rect.colliderect(top_pipe_rect) or
                bird_rect.colliderect(bottom_pipe_rect))

# 创建小鸟和管道列表
bird = Bird()
pipes = []
score = 0
font = pygame.font.Font(None, 36)

# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
    screen.fill((0, 0, 0))

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bird.jump()

    # 小鸟移动
    bird.move()

    # 随机生成管道
    if len(pipes) == 0 or pipes[-1].x < WIDTH - 200:
        pipes.append(Pipe())

    # 移动和绘制管道
    for pipe in pipes[:]:
        pipe.move()
        pipe.draw()
        if pipe.collides_with(bird):
            print("游戏结束，你的得分是:", score)
            running = False
        if not pipe.passed and pipe.x + 50 < bird.x:
            pipe.passed = True
            score += 1
        if pipe.x + 50 < 0:
            pipes.remove(pipe)

    # 绘制小鸟
    bird.draw()

    # 显示得分
    score_text = font.render(f"得分: {score}", True, WHITE)
    screen.blit(score_text, (10, 10))

    # 边界检测
    if bird.y < 0 or bird.y > HEIGHT:
        print("游戏结束，你的得分是:", score)
        running = False

    # 更新显示
    pygame.display.flip()
    clock.tick(30)

# 退出游戏
pygame.quit()